"use strict";

const Service = require("egg").Service;

class UserService extends Service {
    async getStudent() {
        let sql = "select id, username, nickname from user where rid != 1";
        let res = await this.app.mysql.query(sql);
        return res;
    }

    async readListByQuery({ rid, rids }) {
        let sql = "select id, username, nickname from user";
        let res;

        // 查询单个角色对应的用户列表
        if (rid) {
            sql += " where rid = ?";
            res = await this.app.mysql.query(sql, [rid]);
            return res;
        }

        if (rids) {
            sql += " where rid in (";
            let parmas = [];
            rids.split(",").map((item, index, arr) => {
                // 最后一个
                if (index === arr.length - 1) {
                    sql += " ?)";
                    parmas.push(item);
                    return;
                }
                sql += "?, ";
                parmas.push(item);
            });
            res = await this.app.mysql.query(sql, parmas);
            return res;
        }
    }

    async findByUsername(username) {
        let sql = `
            select
            u.*, r.name as rname
            from user as u
            join role as r on u.rid = r.id
            where u.username = ?
        `;
        let params = [username];
        let res = await this.app.mysql.query(sql, params);
        return res[0];
    }

    async add({ username, password, nickname }) {
        let sql =
            "insert into user (username, password, nickname) values (?, ?, ?)";
        let params = [username, this.ctx.helper.encrypt(password), nickname];
        let res = await this.app.mysql.query(sql, params);
        return res;
    }

    /**
     * 根据用户id，获取用户的所有视图权限
     * @param {number} uid
     */
    async getMenuListByUid(uid) {
        let sql = `
            select
                a.name, a.path
            from user as u
                join r_role_acl as rra on u.rid = rra.rid
                join acl as a on rra.aid = a.id and a.type = 1
            where u.id = ?
        `;
        let res = await this.app.mysql.query(sql, [uid]);
        return res;
    }
}

module.exports = UserService;
